<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'bas:mes:price:basInvOperPriceJust:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #basInvOperPriceJustRdsList>
        <!-- :disabled="(record.status != '9') && (record.status)" -->
        <!-- <a-button
          class="mb-2 mr-2"
          @click="handlexzAdd"
          disabled
          v-auth="'bas:mes:price:basInvOperPriceJust:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('选择') }}
        </a-button>

        <a-button
          class="mb-2"
          disabled
          @click="handleBasInvOperPriceJustRdsAdd"
          v-auth="'bas:mes:price:basInvOperPriceJust:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
        <BasicTable
          @register="registerBasInvOperPriceJustRdsTable"
          @row-click="handleBasInvOperPriceJustRdsRowClick"
          @edit-change="rowChange"
        >
          <template #chListSelect="{ record: childRecord, index }">
            <ListSelect
              v-model:value="childRecord.invCode"
              :labelValue="childRecord?.basInv.cinvname"
              ref="tjdchlist"
              disabled
              selectType="basInvSelect"
              @select="handSelectch($event, childRecord)"
            />
          </template>
          <template #gxListSelect="{ record: childRecord }">
            <ListSelect
              v-model:value="childRecord.operCode"
              :labelValue="childRecord?.basOpe?.name"
              ref="tjdgxlist"
              disabled
              selectType="basMesOperSelect"
              @select="handSelectgx($event, childRecord)"
            />
          </template>
        </BasicTable>
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_OperPriceJust"
        completeText="提交"
        :loading="loadingRef"
        :auth="'bas:mes:price:basInvOperPriceJust:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>

    <ListSelect
      ref="tjdlslist"
      v-show="false"
      selectType="basInvOperPriceSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
      @select="handSelect"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasMesPriceBasInvOperPriceJustForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    BasInvOperPriceJust,
    basInvOperPriceJustSave,
    basInvOperPriceJustForm,
  } from '/@/api/bas/mes/price/basInvOperPriceJust';
  import { BpmButton } from '/@/components/Bpm';
  import { formatToDate } from '/@/utils/dateUtil';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('bas.mes.price.basInvOperPriceJust');
  const { showMessage } = useMessage();
  const record = ref<BasInvOperPriceJust>({} as BasInvOperPriceJust);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    // value: record.value.isNewRecord ? t('新增计件调价单') : t('编辑计件调价单'),
    value: t('计件调价单') ,
  }));

  const loadingRef = ref(false);
  let queryParams = ref({});
  let listSelectRef = ref([]);
  let tjdlslist = ref<any>('');

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('调价单号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      // rules: [
      //   { required: true },
      //   { pattern: /^[a-zA-Z0-9_]*$/, message: t('请输入字母数字下划线') },
      // ],
      dynamicDisabled: true,
    },
    {
      label: t('调价日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm' },
      },
      // required: true,
      dynamicDisabled: true,
    },
    {
      label: t('调价说明'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        rows: 5,
      },
      colProps: { lg: 24, md: 24 },
      dynamicDisabled: true,
    },
    {
      label: t('调价人'),
      field: 'creator.userName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('创建时间'),
      field: 'createDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('调价方式'),
      field: 'justType',
      component: 'Select',
      componentProps: {
        dictType: 'mes_Just_type',
        allowClear: true,
      },
      show: false,
    },
    {
      label: t('调价明细'),
      field: 'basInvOperPriceJustRdsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'basInvOperPriceJustRdsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerBasInvOperPriceJustRdsTable, basInvOperPriceJustRdsTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record1: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleBasInvOperPriceJustRdsDelete.bind(this, record1),
    //       },
    //       auth: 'bas:mes:price:basInvOperPriceJust:edit',
    //       // ifShow: () => ((record.value.status == '9') || (!record.value.status)),
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setBasInvOperPriceJustRdsTableData(_res: Recordable) {
    basInvOperPriceJustRdsTable.setColumns([
      {
        title: t('调价方式'),
        dataIndex: 'justType',
        width: 130,
        align: 'center',
        dictType: 'mes_Just_type',
        editRow: false,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'mes_Just_type',
          allowClear: true,
        },
        editRule: true,
      },

      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        width: 200,
        align: 'left',
        slot: 'chListSelect',
      },
      {
        title: t('存货编码'),
        dataIndex: 'invCode',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'ListSelect',
        // editComponentProps: {
        //   selectType: 'empUserSelect',
        // },
        // editRule: true,
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.cinvstd',
        width: 130,
        align: 'left',
      },
      {
        title: t('工序名称'),
        dataIndex: 'oper.name',
        width: 180,
        align: 'left',
        slot: 'gxListSelect',
      },
      {
        title: t('工序编码'),
        dataIndex: 'operCode',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 64,
        // },
        // editRule: true,
      },

      {
        title: t('计件单价'),
        dataIndex: 'iprice',
        width: 130,
        align: 'center',
        editRow: false,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: true,
      },
      {
        title: t('生效日期'),
        dataIndex: 'enDate',
        width: 150,
        align: 'center',
        editRow: false,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          // showTime: { format: 'HH:mm' },
        },
        editRule: true,
      },
      {
        title: t('失效日期'),
        dataIndex: 'exDate',
        width: 150,
        align: 'center',
        editRow: false,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          // showTime: { format: 'HH:mm' },
        },
        editRule: true,
      },
      {
        title: t('单价说明'),
        dataIndex: 'remarks',
        width: 180,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
      {
        title: t('价格表ID'),
        dataIndex: 'priceId',
        width: 130,
        align: 'left',
        ifShow: false,
      },
      {
        title: t('ID'),
        dataIndex: 'id',
        width: 130,
        align: 'left',
        ifShow: false,
      },
      {
        title: t('主表ID'),
        dataIndex: 'parentId',
        width: 130,
        align: 'left',
        ifShow: false,
      },
    ]);
    basInvOperPriceJustRdsTable.setTableData(record.value.basInvOperPriceJustRdsList || []);
  }

  function handleBasInvOperPriceJustRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleBasInvOperPriceJustRdsAdd() {
    console.log('handleBasInvOperPriceJustRdsAdd');
    basInvOperPriceJustRdsTable.insertTableDataRecord({
      id: new Date().getTime(),
      rowId: new Date().getTime(),
      isNewRecord: true,
      editable: true,
      justType: '1',
      invCode: '',
      operCode: '',
      iprice: '',
      enDate: '',
      exDate: '',
      priceId: '',
      basInv: {
        cinvname:'',
        cinvstd: '',
      },
      oper: {
        name: '',
      }
    });
  }
  function handlexzAdd() {
    // basInvOperPriceJustRdsTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
    listSelectRef.value = [];
    tjdlslist.value.handleInputClick();
  }

  async function handSelectch(selectData, childRecord) {
    // let arr = await basInvOperPriceJustRdsTable.getDataSource();
    // console.log(selectData, childRecord, arr, '======');
    basInvOperPriceJustRdsTable.updateTableDataRecord(childRecord.id, {
      ...childRecord,
      invCode: selectData[0].cinvcode,
      basInv: {
        cinvname:selectData[0].cinvname,
        cinvstd: selectData[0].cinvstd,
      },
    });
  }
  async function handSelectgx(selectData, childRecord) {
    console.log(selectData, childRecord);
    basInvOperPriceJustRdsTable.updateTableDataRecord(childRecord.id, {
      ...childRecord,
      operCode: selectData[0].code,
      oper: {
        name: selectData[0].name,
      }
    });
  }
  async function handSelect(selectData) {
    console.log(selectData);
    let arr = await basInvOperPriceJustRdsTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.invCode == item.invCode) {
          flag = false;
        }
      });
      if (flag) {
        basInvOperPriceJustRdsTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          justType: '2',
          status:''
          // projectno: item.pcode,
          // munit: item.unit,
          // iqty: item.num,
        });
      }
    });
  }

  async function rowChange({ column, value, record }) {
    console.log(column, value, record, '========');
  }

  function handleBasInvOperPriceJustRdsDelete(record: Recordable) {
    basInvOperPriceJustRdsTable.deleteTableDataRecord(record);
  }

  async function getBasInvOperPriceJustRdsList() {
    let basInvOperPriceJustRdsListValid = true;
    let basInvOperPriceJustRdsList: Recordable[] = [];
    for (const record of basInvOperPriceJustRdsTable.getDataSource()) {
      // if (!(await record.onEdit?.(false, true))) {
      //   basInvOperPriceJustRdsListValid = false;
      // }
      basInvOperPriceJustRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of basInvOperPriceJustRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      basInvOperPriceJustRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!basInvOperPriceJustRdsListValid) {
      throw { errorFields: [{ name: ['basInvOperPriceJustRdsList'] }] };
    }
    return basInvOperPriceJustRdsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await basInvOperPriceJustForm(data);

    record.value = (res.basInvOperPriceJust || {}) as BasInvOperPriceJust;
    record.value.ddate = record.value.ddate || formatToDate(new Date());
    record.value.__t = new Date().getTime();

    setFieldsValue(record.value);
    setBasInvOperPriceJustRdsTableData(res);
    updateSchema([
      {
        field: 'djno',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      data.basInvOperPriceJustRdsList = await getBasInvOperPriceJustRdsList();
      // console.log('submit', params, data, record);
      const res = await basInvOperPriceJustSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
